﻿@page "/SysOrder"
@using SelfService.ViewModel.SysOrderVMs;
@using SelfService.Model.Models
@using SelfService.Model.Request
@inherits BasePage
@attribute [ActionDescription("缴费订单", "SelfService.Controllers,SysPrescription")]

<WTSearchPanel OnSearch="@DoSearch">
    <ValidateForm Model="@_searchModel">
        <Row ItemsPerRow="ItemsPerRow.Three" RowType="RowType.Inline">
            <BootstrapInput @bind-Value="@_searchModel.CardNo"/>
            <BootstrapInput @bind-Value="@_searchModel.JiuZhenNo"/>
            <BootstrapInput @bind-Value="@_searchModel.JieSuanNo"/>
            <BootstrapInput @bind-Value="@_searchModel.Department"/>
            <BootstrapInput @bind-Value="@_searchModel.Doctor"/>
            <BootstrapInput @bind-Value="@_searchModel.OrderTime"/>
            <Select @bind-Value="@_searchModel.Status"  PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
            <Select @bind-Value="@_searchModel.Type"  PlaceHolder="@WtmBlazor.Localizer["Sys.All"]"></Select>
        </Row>
    </ValidateForm>
</WTSearchPanel>

<Table @ref="_dataTable" 
        TItem="SysPrescriptionView" 
        OnQueryAsync="OnSearch" 
        IsPagination="true" 
        IsStriped="true" 
        IsBordered="true" 
        ShowRefresh="false"
        ShowToolbar="true"
        ShowLoading="true"
        IsMultipleSelect="true" 
        ShowExtendButtons="true" 
        ShowExtendDeleteButton="false"
        ShowExtendEditButton="false"
        ExtendButtonColumnAlignment="Alignment.Left"
        IsExtendButtonsInRowHeader="true"
        ShowDefaultButtons="false" 
       style="margin-top:10px;">
    <TableColumns>
        <TableColumn @bind-Field="@context.PatientName"/>
        <TableColumn @bind-Field="@context.CardNo"/>
        <TableColumn @bind-Field="@context.Code"/>
        <TableColumn @bind-Field="@context.TradeNo"/>
        <TableColumn @bind-Field="@context.Department"/>
        <TableColumn @bind-Field="@context.Doctor"/>
        <TableColumn @bind-Field="@context.Projects"/>
        <TableColumn @bind-Field="@context.Amount" FormatString="#0.00"/>
        <TableColumn @bind-Field="@context.FundAmount" FormatString="#0.00"/>
        <TableColumn @bind-Field="@context.AccountAmount" FormatString="#0.00"/>
        <TableColumn @bind-Field="@context.ReimbursementAmount" FormatString="#0.00"/>
        <TableColumn @bind-Field="@context.SelfAmount" FormatString="#0.00"/>
        <TableColumn @bind-Field="@context.Status"/>
        <TableColumn @bind-Field="@context.SocialSecurityStatus"/>
        <TableColumn @bind-Field="@context.CreateTime" FormatString="yyyy-MM-dd HH:mm:ss"/>
    </TableColumns>
    <TableToolbarTemplate>
        @if (IsAccessable("/api/SysPrescription/BatchDelete"))
        {
            <TableToolbarPopconfirmButton 
                TItem="SysPrescriptionView" 
                Color="Color.Primary"
                Icon="fa fa-fw fa-trash-o" 
                Text="@WtmBlazor.Localizer["Sys.BatchDelete"]"
                OnConfirm="@OnBatchDeleteClick" 
                Content="@WtmBlazor.Localizer["Sys.BatchDeleteConfirm"]" 
                CloseButtonText="@WtmBlazor.Localizer["Sys.Close"]"
                ConfirmButtonText="@WtmBlazor.Localizer["Sys.BatchDelete"]" ConfirmButtonColor="Color.Danger" />
        }
        @if (IsAccessable("/api/SysPrescription/ExportExcel"))
        {
            <TableToolbarButton 
                TItem="SysPrescriptionView" 
                Color="Color.Primary" 
                Icon="fa fa-fw fa-download" 
                Text="@WtmBlazor.Localizer["Sys.Export"]" 
                OnClickCallback="@OnExportClick" IsAsync="true" />
        }
    </TableToolbarTemplate>
    <RowButtonTemplate>
        <div style="padding-right:10px;">
            @if (IsAccessable("/api/SysPrescription/{id}"))
            {
                <TableCellButton 
                    Size="Size.ExtraSmall" 
                    Color="Color.Info" 
                    Icon="fa fa-info" 
                    Text="@WtmBlazor.Localizer["Sys.Details"]" 
                    OnClick="()=>OnDetailsClick(context)" />
            }
            @if (IsAccessable("/api/SysPrescription/BatchDelete"))
            {
                <PopConfirmButton 
                    Icon="fa fa-trash-o" 
                    Text="@WtmBlazor.Localizer["Sys.Delete"]" 
                    OnConfirm="() => OnDeleteClick(context)" 
                    Color="Color.Danger" Size="Size.ExtraSmall"
                    Content="@WtmBlazor.Localizer["Sys.DeleteConfirm"]" 
                    CloseButtonText="@WtmBlazor.Localizer["Sys.Close"]" 
                    ConfirmButtonText="@WtmBlazor.Localizer["Sys.Delete"]" 
                    ConfirmButtonColor="Color.Danger" />
            }
            @if (IsAccessable("/api/SysPrescription/Refund/{id}"))
            {
                <TableCellPopconfirmButton 
                    Icon="fa fa-badge-dollar" 
                    Text="退款"
                    OnConfirm="() => OnRefundClick(context)" 
                    Color="Color.Warning" 
                    Size="Size.ExtraSmall"
                    Content="确定要发起退款吗?" 
                    CloseButtonText="取消"
                    ConfirmButtonText="退款" 
                    IsShow="context.Status is SysOrderStatus.已缴费 or SysOrderStatus.退款失败"
                    ConfirmButtonColor="Color.Warning" />
            }
        </div>
    </RowButtonTemplate>
</Table>

@code{

    private readonly SysOrderSearcher _searchModel = new();
    private Table<SysPrescriptionView> _dataTable;


    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    private async Task<QueryData<SysPrescriptionView>> OnSearch(QueryPageOptions opts)
    {
        return await StartSearch<SysPrescriptionView>("/api/SysPrescription/Search", _searchModel, opts);
    }

    private void DoSearch()
    {
        _dataTable.QueryAsync();
    }
    
    private async Task OnDetailsClick(SysPrescriptionView item)
    {
        await OpenDialog<Details>(WtmBlazor.Localizer["Sys.Details"], x => x.id == item.ID.ToString());
    }

    private async Task OnBatchDeleteClick()
    {
        if (_dataTable.SelectedRows?.Any() == true)
        {
            await PostsData(_dataTable.SelectedRows.Select(x => x.ID).ToList(), $"/api/SysPrescription/batchdelete", (s) => WtmBlazor.Localizer["Sys.BatchDeleteSuccess", s]);
            await _dataTable.QueryAsync();
        }
        else
        {
            await WtmBlazor.Toast.Information(WtmBlazor.Localizer["Sys.Info"], WtmBlazor.Localizer["Sys.SelectOneRowMin"]);
        }
    }

    private async Task OnDeleteClick(SysPrescriptionView item)
    {
        await PostsData(new List<string> { item.ID.ToString() }, $"/api/SysPrescription/batchdelete", (s) => "Sys.OprationSuccess");
        await _dataTable.QueryAsync();
    }


    private async Task OnExportClick(IEnumerable<SysPrescriptionView> items)
    {
        if (_dataTable.SelectedRows?.Any() == true)
        {
            await Download("/api/SysPrescription/ExportExcelByIds", _dataTable.SelectedRows.Select(x => x.ID.ToString()).ToList());
        }
        else
        {
            await Download("/api/SysPrescription/ExportExcel", _searchModel);
        }
    }
    
    private async Task OnRefundClick(SysPrescriptionView item)
    {
        if (item.PayId != null)
        {
            //向HIS发起处方退款请求, 如果HIS处理成功则发起退款. 否则联系HIS检查无法退款原因
            var result = await WtmBlazor.Api.CallAPI<Result<object>>($"/api/SysPrescription/Refund?id={item.ID}");
            if (result != null && result.Data.Code == 200)
            {
                var postData = new PayRefundRequest()
                {
                    PayId = (Guid)item.PayId,
                    PrescriptionId = item.ID
                };
                result = await WtmBlazor.Api.CallAPI<Result<object>>($"/api/SysPay/Refund", HttpMethodEnum.POST, postData);
                if (result?.Data.Code == 200)
                {
                    await WtmBlazor.Toast.Success("提示", $"退款请求已经发起, 退款信息:用户[{item.PatientName}], 金额:￥{item.Amount}元, 请稍后查询结果！");
                    await _dataTable.QueryAsync();
                    StateHasChanged();
                    return;
                }
            }
            await WtmBlazor.Toast.Error("错误", $"退款失败, {result?.Data?.Message}, 退款信息:用户[{item.PatientName}], 金额:￥{item.Amount}元.", false);
            await _dataTable.QueryAsync();
        }
        else
        {
            await WtmBlazor.Toast.Success("错误", $"退款失败, PayId不能为空");
        }
    }
}
